<template>
  <div class="app-container">

    <!--设备信息from表单查询信息 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">

      <el-form-item :label="$t('device.center.deviceCode')" prop="deviceCode">
        <el-input v-model="queryParams.deviceCode" :placeholder="$t('device.center.placeholder.deviceCode')" clearable
          style="width: 240px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('device.center.iccid')" prop="iccid">
        <el-input v-model="queryParams.iccid" :placeholder="$t('device.center.placeholder.iccid')" clearable
          style="width: 240px" @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item :label="$t('device.type.selectTypeId')" prop="deviceTypeId" label-width="120px">
        <el-select v-model="queryParams.deviceTypeId" clearable :placeholder="$t('device.type.placeholder.selectTypeId')"
          @change="deviceTypeChange">
          <el-option v-for="item in deviceTypeOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('device.model.selectModelId')" prop="deviceModelId" label-width="120px">
        <el-select v-model="queryParams.deviceModelId" clearable
          :placeholder="$t('device.model.placeholder.selectModelId')">
          <el-option v-for="item in deviceModelOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('device.center.vehicleVin')" prop="vehicleVin">
        <el-input v-model="queryParams.vehicleVin" :placeholder="$t('device.center.placeholder.vehicleVin')" clearable
          style="width: 240px" @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item :label="$t('device.center.status')" prop="status">
        <el-select v-model="queryParams.status" :placeholder="$t('device.center.placeholder.status')" clearable>
          <el-option v-for="dict in dict.type.device_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('device.center.bindStatus')" prop="bindStatus">
        <el-select v-model="queryParams.bindStatus" :placeholder="$t('device.center.placeholder.bindStatus')" clearable>
          <el-option v-for="dict in dict.type.device_bind_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t('common.button.query')
        }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('common.button.reset') }}</el-button>
      </el-form-item>
    </el-form>

    <!--设备新增入口-->
    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['device:center:add']">{{ $t('common.button.add') }}</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="openImport"
          v-hasPermi="['device:center:import']">{{ $t('common.button.import') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['device:center:export']">{{ $t('common.button.export') }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['device:center:delete']">{{ $t('common.button.delete') }}
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!--设备Table信息-->
    <el-table v-loading="loading" :data="tableData" style="width: 100%" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column :label="$t('device.center.deviceCode')" prop="deviceCode" width="180"></el-table-column>
      <el-table-column :label="$t('device.center.deviceTypeName')" prop="deviceTypeName" align="center"
        width="80"></el-table-column>
      <el-table-column :label="$t('device.center.deviceModelName')" prop="deviceModelName" align="center"
        width="80"></el-table-column>

      <el-table-column :label="$t('device.center.status')" align="center" prop="status" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.device_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('device.center.bindStatus')" align="center" prop="bindStatus" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.device_bind_status" :value="scope.row.bindStatus" />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" align="center" :label="$t('device.center.createTime')" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="bindingTime" align="center" :label="$t('device.center.bindingTime')" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.bindingTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="userCode" align="center" :label="$t('device.center.userCode')" width="150"
        :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="iccid" align="center" :label="$t('device.center.iccid')" width="200"
        :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="msisdn" align="center" :label="$t('device.center.msisdn')" width="150"
        :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="cardState" align="center" :label="$t('device.center.cardState')"
        width="120"></el-table-column>
      <el-table-column prop="vehicleVin" align="center" :label="$t('device.center.vehicleVin')" width="150"
        :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="vehicleEngineNo" align="center" :label="$t('device.center.vehicleEngineNo')" width="150"
        :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="softwareVersion" align="center" :label="$t('device.center.softwareVersion')" width="150"
        :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="hardwareVersion" align="center" :label="$t('device.center.hardwareVersion')" width="150"
        :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="modemSoftware" align="center" :label="$t('device.center.modemSoftware')" width="150"
        :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="modemHardware" align="center" :label="$t('device.center.modemHardware')" width="150"
        :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="deviceBlueName" align="center" :label="$t('device.center.deviceBlueName')" width="150"
        :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="deviceBlueMac" align="center" :label="$t('device.center.deviceBlueMac')" width="150"
        :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="desKey" align="center" :label="$t('device.center.deviceMcuKey')" width="150"
        :show-overflow-tooltip="true"></el-table-column>
        <el-table-column :label="$t('common.table.operate')" align="center" fixed="right" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)"
                        v-hasPermi="['vehicle:type:edit']">{{ $t('common.button.edit') }}</el-button>
                </template>
            </el-table-column>
    </el-table>

    <!-- 添加或修改设备对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="550px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="200px">
        <el-form-item w :label="$t('device.center.deviceCode')" prop="deviceCode" >
          <el-input disabled v-model="form.deviceCode" placeholder="请输入设备编码"  />
        </el-form-item>
        <el-form-item :label="$t('device.type.selectTypeId')" prop="deviceTypeId">
          <el-select disabled v-model="form.deviceTypeId" clearable size="small" style="width: 240px" @change="deviceTypeChange">
          <el-option v-for="dict in deviceTypeOptions"
                     :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
        </el-form-item>
        <el-form-item :label="$t('device.model.selectModelId')" prop="deviceModelId">
          <el-select disabled v-model="form.deviceModelId" clearable size="small" style="width: 240px">
          <el-option v-for="dict in deviceModelOptions"
                     :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
        </el-form-item>
        <el-form-item :label="$t('device.center.iccid')" prop="iccid">
          <el-input v-model="form.iccid" placeholder="请输入设备ICCID" />
        </el-form-item>
        <el-form-item :label="$t('device.center.deviceBlueName')" prop="deviceBlueName">
          <el-input v-model="form.deviceBlueName" placeholder="请输入设备蓝牙名称" />
        </el-form-item>
        <el-form-item :label="$t('device.center.deviceBlueMac')" prop="deviceBlueMac">
          <el-input v-model="form.deviceBlueMac" placeholder="请输入设备蓝牙MAC地址" />
        </el-form-item>
        <el-form-item label="设备协议加密key" prop="desKey">
          <el-input disabled v-model="form.desKey" placeholder="请输入设备协议加密key" />
        </el-form-item>
        
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!--分页-->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
      <center-import ref="centerImport" @refreshData="getList"></center-import>

  </div>
</template>

<script>
import { listDevice, delDevice,addDevice,updateDevice } from "@/api/device/center";
import CenterImport from "./centerImport";
import { typeTree } from "@/api/device/type";
import { modelTree } from "@/api/device/model";

export default {
  name: "deviceCenter",
  dicts: ['device_status', 'device_bind_status'],
  components: { CenterImport },
  data() {
    return {
      // 表单参数
      form: {},
      deviceTypeOptions: [],
      deviceModelOptions: [],
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      //选中设备的绑定状态数组
      deviceStatus:[],
      deviceCodes: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备表格数据
      tableData: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceCode: undefined,
        iccid: undefined,
        deviceType: undefined,
        deviceModel: undefined,
        status: undefined,
        bindStatus: undefined,
        vehicleVin: undefined,
        deviceTypeId: undefined,
        deviceModelId: undefined,
      },
      rules: {
        id: [
          { required: true, message: "ID不能为空", trigger: "blur" }
        ],
        deviceCode: [
          { required: true, message: "设备编码不能为空", trigger: "blur" }
        ],
        deviceModelId: [
          { required: true, message: "设备型号不能为空", trigger: "blur" }
        ],
        deviceTypeId: [
          { required: true, message: "设备类型不能为空", trigger: "change" }
        ],
        encryptionId: [
          { required: true, message: "设备加密ID不能为空", trigger: "blur" }
        ],
        vehicleCode: [
          { required: true, message: "绑定车辆CODE不能为空", trigger: "blur" }
        ],
        iccid: [
          { required: true, message: "设备ICCID不能为空", trigger: "blur" }
        ],
        bindstatus: [
          { required: true, message: "设备绑定状态：0未绑定，1绑定中，2已解绑不能为空", trigger: "change" }
        ],
        activeTime: [
          { required: true, message: "设备首次登录平台时间不能为空", trigger: "blur" }
        ],
        deviceBlueName: [
          { required: true, message: "设备蓝牙名称不能为空", trigger: "blur" }
        ],
        deviceBlueMac: [
          { required: true, message: "设备蓝牙MAC地址不能为空", trigger: "blur" }
        ],
        desKey: [
          { required: true, message: "设备协议加密key不能为空", trigger: "blur" }
        ],
        devicePassword: [
          { required: true, message: "设备密码不能为空", trigger: "blur" }
        ],
        bindingTime: [
          { required: true, message: "设备绑定时间不能为空", trigger: "blur" }
        ],
        loginStatus: [
          { required: true, message: "设备登录状态：1未登录，2登录不能为空", trigger: "change" }
        ],
        softwareVersion: [
          { required: true, message: "mcu软件版本不能为空", trigger: "blur" }
        ],
        hardwareVersion: [
          { required: true, message: "mcu硬件版本不能为空", trigger: "blur" }
        ],
        modemSoftware: [
          { required: true, message: "modem软件版本不能为空", trigger: "blur" }
        ],
        modemHardware: [
          { required: true, message: "modem硬件版本不能为空", trigger: "blur" }
        ],
        gpsStatus: [
          { required: true, message: "gps上报状态：1未上报，2已上报不能为空", trigger: "change" }
        ],
        onlineStatus: [
          { required: true, message: "设备在线状态：1离线，2在线不能为空", trigger: "change" }
        ],
        gpsTemp: [
          { required: true, message: "gps点临时存储不能为空", trigger: "blur" }
        ],
        mileage: [
          { required: true, message: "设备临时里程存储不能为空", trigger: "blur" }
        ],
      }
    }
  },
  computed: {},
  watch: {},
  created() {
    if (this.$route.query) {
            this.queryParams.deviceCode = this.$route.query.deviceCode;
        }
    this.getList();
    this.getTypeTree();
  },
  mounted() {
  },
  methods: {
    deviceTypeChange(typeId) {
      if (typeId) {
        this.getModelTree(typeId)
      } else {
        this.queryParams.deviceModelId = undefined
        this.deviceModelOptions = []
      }
    },
    getTypeTree() {
      typeTree().then(response => {
        this.deviceTypeOptions = response.data;
      });
    },
    getModelTree(typeId) {
      modelTree(typeId).then(response => {
        this.deviceModelOptions = response.data;
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.deviceCodes = selection.map(item => item.deviceCode);
      this.deviceStatus = selection.map(item => item.bindStatus);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 查询设备列表 */
    getList() {
      this.loading = true;
      listDevice(this.queryParams).then(response => {
        this.tableData = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    openImport() {
      this.$refs['centerImport'].init()
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const status = this.deviceStatus.filter(x =>
        x == 1
      )
      if (status.length > 0) {
        this.$message.error(this.$t("device.tip.deleteFailure"))
        return;
      }
      const ids = row.id || this.ids;
      const deviceCodes = row.deviceCode || this.deviceCodes;
      const options = this.$t('common.message.tip.confirm', {
        operate: this.$t('common.operate.type.delete'),
        name: this.$t('device.center.deviceCode'),
        data: deviceCodes
      })
      this.$modal.confirm(options).then(function () {
        return delDevice(deviceCodes);
      }).then(() => {
        this.getList();
        this.$modal.deleteSuccess();
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const thiz = this
      const message = this.$t('device.center.exportInfo');
      const title = this.$t('common.prompt.tip');
      this.$confirm(message, title, {
        confirmButtonText: this.$t('common.button.confirm'),
        cancelButtonText: this.$t('common.button.cancel'),
        type: "warning",
      }).then(function () {
        thiz.download('/device/center/export', {
          ...thiz.queryParams
        }, `device_${new Date().getTime()}.xlsx`)
      })
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备"
    },
    handleEdit(row) {
      this.reset();

      console.log("设备：",row);
      this.form = row;
      console.log("表格",this.form);
      this.open = true;
      this.title = "修改设备"
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateDevice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addDevice(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        deviceCode: undefined,
        deviceModel: undefined,
        deviceType: undefined,
        encryptionId: undefined,
        vehicleCode: undefined,
        iccid: undefined,
        bindstatus: undefined,
        activeTime: undefined,
        deviceBlueName: undefined,
        deviceBlueMac: undefined,
        desKey: undefined,
        devicePassword: undefined,
        bindingTime: undefined,
        loginStatus: undefined,
        softwareVersion: undefined,
        hardwareVersion: undefined,
        modemSoftware: undefined,
        modemHardware: undefined,
        gpsStatus: undefined,
        onlineStatus: undefined,
        gpsTemp: undefined,
        mileage: undefined,
        createTime: undefined,
        updateTime: undefined,
        createBy: undefined,
        updateBy: undefined
      };
      this.resetForm("form");
    },
  }
}
</script>
<style>
.el-input__inner{
  width:240px;
}
</style>
